<?php

namespace App\Http\Controllers\Admin;

use App\Models\Permission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PermissionsController extends Controller
{
    public function index(){
        $permissions = Permission::orderby('id', 'desc')->paginate(config('constants.page_num'));

        return view('admin.permissions.index', compact('permissions'));
    }

    public function create(){
        return view('admin.permissions.create');
    }

    public function store(Request $request){
        $this->validate($request, [
            'name' => 'required|max:255',
        ]);
        $permission = Permission::create($request->all());
        if($permission){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/permissions')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$permission)));
        }
    }

    public function edit($id){
        $perm = Permission::findOrFail($id);
        return view('admin.permissions.edit', compact('perm'));
    }

    public function update(Request $request, $id){
        $perm = Permission::findOrFail($id);
        $this->validate($request, [
            'name' => 'required|max:255',
        ]);
        $result = $perm->update($request->all());
        if($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/permissions')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $role = Permission::findOrFail($id);
        if ($role->delete()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }
}
